require("sdk/urlcode") 

taobao=class() 

function taobao:ctor(data)  -- 定义 base_type 的构造函数 
    self.data=data

    self.url="http://gw.api.taobao.com/router/rest"
    self.version="2.0"

end



function taobao:query(method,callback,fields) 
	local params={
		  {key="method",value=method},
	      {key="timestamp",value=os.date("%Y-%m-%d %H:%I:%S", os.time())},
	      {key="format",value="json"},
	      {key="app_key",value=self.data.app_key},
	      {key="v",value=self.version},
	      {key="sign_method",value="md5"},
	      {key="session",value=self.data.access_token},
	} 
	if fields then
		table.insert(params,{key="fields",value=fields});
	end

	table.sort( params,  function(a,b)
								return	a.key<b.key
							end
				)
	local signStr=self.data.app_secret
	local requestParams = ""
	for key, value in pairs(params) do   
 	   signStr=signStr..value.key..value.value 
 	   requestParams=requestParams.."&"..value.key.."="..urlencode(value.value)
	end 	
	signStr=signStr..self.data.app_secret 

	local  sign =string.upper(CCCrypto:MD5Lua(signStr,false))
	local  url = self.url.."?sign="..sign..requestParams
   


   	local request =CCHTTPRequest:createWithUrlLua(
					function(event)
						local request = event.request 
 					  	local cjson = require "cjson"
						local backparam = cjson.decode(request:getResponseString()) 
  					  
  					  	print(request:getResponseString())
						callback(backparam)
  
					end, 
					url,
					kCCHTTPRequestMethodPOST)
	request:start()
end


